import React, {useState, useEffect} from 'react';
import {Link, useHistory} from 'react-router-dom';

import {
    Form,
    Input,
    InputNumber,
    Button,
    Checkbox,
    Row,
    Col,
    Upload,
    Cascader,
    Select,
    Radio,
    DatePicker,
    Tabs,
    TimePicker,
    message
} from 'antd';

const {Option} = Select;
const {RangePicker} = DatePicker;
const {TabPane} = Tabs;
const {Group: CheckboxGroup} = Checkbox;


import Ckeditor from '@src/components/ckeditor/Ckeditor';
import axios from '@src/lib/axios';
import moment from 'moment';
import '@src/style/hotel.scss';

function BaseInfo({area, supplie, onChangeHandler, hotel_id, activeKey}) {
    const history = useHistory();
    const [form] = Form.useForm();
    const [ck, setCk] = useState([
        {indeterminate: false, ckeckAll: false},
        {indeterminate: false, ckeckAll: false},
        {indeterminate: false, ckeckAll: false},
    ]);

    //早餐选项部分
    const [disableBreakFirst, setDisableBreakFirst] = useState(true);

    const [lbs, setLbs] = useState();
    const [loading, setLoading] = useState(false);
    const [hotelTypeConf, setHotelTypeConf] = useState([]);
    const [brandTypeConf, setBrandTypeConf] = useState([]);
    const [starLevelConf, setStarLevelConf] = useState([]);
    const [attractionConf,setAttractionConf] = useState([]);
    const [hotFocus, setHotFocus] = useState([]);
    const [servicesConf, setServicesConf] = useState([]);
    const [facilitiesConf, setFacilitiesConf] = useState([]);


    let ck1 = '';
    let ck2 = '';
    let ck3 = '';


    useEffect(() => {
        setLbs(`${process.env.LBS_QQ}`);
        //拉取酒店类型配置
        getHotelTypeConfig();
        //拉取酒店品牌配置
        getHotelBrandType();
        //酒店星级配置
        getHotelStarType();
        //热门关注配置
        getHotFocusConf();
        //酒店服务
        getServicesConf();
        //设施配置
        getFacilitiesConf();
        //获取系统景点配置信息
        getAttraction();

        if (hotel_id && activeKey === '1') {

            axios.post('/product/hotel/info', {hotel_id}).then(res => {
                if (res.code === 0) {
                    let data = res.data;
                    let {
                        simple_desc, detail_traffic_desc, children_append_bed, facility_ids, services, focus, stay_stime, check_out_stime,
                        opening_date, decorate_date, city_id, have_breakfast
                    } = data;
                    // data.facility_ids = facility_ids;
                    // data.services = services.split(',');
                    // data.focus = focus.split(',');
                    data.city_id = city_id ? city_id : [];
                    if (!!stay_stime) {
                        data.stay_stime = moment(stay_stime, 'HH:mm');
                    }

                    if (!!check_out_stime) {
                        data.check_out_stime = moment(check_out_stime, 'HH:mm');
                    }
                    data.opening_date = opening_date && moment(opening_date);
                    data.decorate_date = decorate_date && moment(decorate_date);
                    if (have_breakfast === 1) {
                        setDisableBreakFirst(false)
                    } else {
                        setDisableBreakFirst(true)
                    }
                    // let attractionId = data['attractions_id'];
                    // let newForm = paramsForm;
                    // newForm.attractions_id = attractionId;
                    // console.log(newForm);
                    // setParamsForm(newForm);
                    // delete data['attractions_id'];
                    ck1 && ck1.setData(simple_desc);
                    ck2 && ck2.setData(detail_traffic_desc);
                    ck3 && ck3.setData(children_append_bed);
                    form.setFieldsValue({
                        ...data
                    })
                }
            })
        }
    }, [hotel_id]);

    let getFacilitiesConf = () => {
        axios.post('/platform/hotel/conf/facilities/list').then(res => {
            if (res.code === 0) {
                let {data} = res;
                console.log('fac', data);
                let tmp = [];
                data.forEach(function (item) {
                    tmp.push({"label": item.title, "value": item.id})
                })
                setFacilitiesConf(tmp)
            }
        })

    }
    //服务配置
    let getServicesConf = () => {
        axios.post('/platform/hotel/conf/services/list').then(res => {
            if (res.code === 0) {
                let {data} = res;
                let tmp = [];
                data.forEach(function (item) {
                    tmp.push({"label": item.title, "value": item.id})
                })
                setServicesConf(tmp)
            }
        })
    }
    //热门关注配置
    let getHotFocusConf = () => {
        axios.post('/platform/hotel/conf/focus/list').then(res => {
            if (res.code === 0) {
                let {data} = res;
                let tmp = [];
                data.forEach(function (item) {
                    tmp.push({"label": item.title, "value": item.id})
                })
                setHotFocus(tmp)
            }
        })
    }
    //获取酒店类型配置信息
    let getHotelTypeConfig = () => {
        axios.post('/platform/hotel/conf/type/list').then(res => {
            if (res.code === 0) {
                let {data} = res;
                let hotelTypeConfTmp = [];
                data.forEach(function (item) {
                    hotelTypeConfTmp.push({"label": item.conf_name, "value": item.id})
                })
                setHotelTypeConf(hotelTypeConfTmp)
            }
        })
    }
    //获取酒店品牌配置
    let getHotelBrandType = () => {
        axios.post('/platform/hotel/conf/brand/list', {"type": 1}).then(res => {
            if (res.code === 0) {
                let {data} = res;
                let brandConfTmp = [];
                data.forEach(function (item) {
                    brandConfTmp.push({"label": item.title, "value": item.id})
                })
                setBrandTypeConf(brandConfTmp)
            }
        })
    }
    //获取星级配置
    let getHotelStarType = () => {
        axios.post('/platform/hotel/conf/star/list').then(res => {
            if (res.code === 0) {
                let {data} = res;
                let starLevelTmp = [];
                data.forEach(function (item) {
                    starLevelTmp.push({"label": item.title, "value": item.id})
                })
                setStarLevelConf(starLevelTmp)
            }
        })
    }
    //获取系统景点列表
    let getAttraction = () =>{
        axios.post('/platform/common/conf/attractions/list_all').then(res=>{
            if (res.code === 0) {
                let {data} = res;
                let attractionConfTmp = [];
                data.forEach(function (item,index) {
                    attractionConfTmp.push(<Option key={index} value={item.id}>{item.title}</Option>);
                })
                setAttractionConf(attractionConfTmp)
            }
        })
    }


    let params = {
        "attractions_id":[],
        "hotel_name": "",
        // "company_id": '',
        "subtitle": "",
        "city_id": [],
        // "type_id":"",
        // "hotel_star_level":1,
        // "brand_id":"",
        "contact_way": "",
        "opening_date": '',
        "decorate_date": '',
        "hotel_address": "",
        scenic: '',
        "simple_desc": "",
        "detail_traffic_desc": "",
        "facility_ids": [],
        "services": [],
        "focus": [],

        //"children_append_bed": "",
        "stay_stime": "",
        "check_out_stime": "",
    }

    let onFinish = (value) => {
        console.log(value)
    };
    let onFinishFailed = (value) => {
        console.log(value)
    };

    let ckChangeHandler = (k, instan) => {
        form.setFieldsValue({[k]: instan.getData()});
    };

    let ckReadyHandler = (instan, vk) => {
        instan.setData(form.getFieldValue(vk));
    };


    let onCheckAllChange = (k, check) => {
        const checked = check.target.checked;
        console.log('checked', checked)
        if (k === 0) {
            form.setFieldsValue({focus: checked && hotFocus.map(item => item.value) || []});
        } else if (k === 1) {
            form.setFieldsValue({services: checked && servicesConf.map(item => item.value) || []});
        } else {
            form.setFieldsValue({facility_ids: checked && facilitiesConf.map(item => item.value) || []});
        }
    }
    let onChange = () => {

    }
    let onSubmit = () => {
        setLoading(true);
        form.validateFields().then((val) => {
            let data = {...form.getFieldsValue()};
            let {facility_ids, services, focus, opening_date, decorate_date, city_id} = data;

            data.facility_ids = facility_ids ? facility_ids.join(',') : [];
            data.services = services ? services.join(',') : [];
            data.focus = focus.join(',');
            data.city_id = city_id;
            if (data.stay_stime !== '') {
                data.stay_stime = data.stay_stime.format('HH:mm');
            }
            if (data.check_out_stime !== '') {
                data.check_out_stime = data.check_out_stime.format('HH:mm');
            }
            data.opening_date = opening_date && opening_date.format('YYYY-MM-DD');
            data.decorate_date = decorate_date && decorate_date.format('YYYY-MM-DD');
            if (hotel_id) {
                data = {...data, hotel_id};
            }
            axios.post('/product/hotel/save', data).then(res => {
                setLoading(false);
                if (res.code === 0) {
                    message.success(hotel_id ? '编辑成功！' : '添加成功！');
                    if (hotel_id) {
                        history.push('/hotel/list');
                    } else {
                        history.push({state: {...history.location.state, hotel_id: res.data.hotel_id}});
                        onChangeHandler('activeKey', '2');
                        onChangeHandler('hotel_id', res.data.hotel_id);
                    }
                } else {
                    message.error(res.msg);
                }
            }).catch(e => setLoading(false));
        }).catch(e => {
            setLoading(false);
            console.log('校验失败,', e)
        });
    }


    let breakfastChange = (e) => {

        if (e.target.value === 1) {
            setDisableBreakFirst(false);
        } else {
            setDisableBreakFirst(true);
        }
    }


    let areaOnChange = (city_id) => {
        form.setFieldsValue({city_id});
    }

    let handleChange = (value) => {
        console.log(`selected ${value}`);
    }

    return (
        <div className="container" style={{position: 'relative'}}>
            <Form
                form={form}
                labelCol={{span: 2}}
                wrapperCol={{span: 20}}
                name="basic"
                initialValues={params}
                onFinish={onFinish}
            >
                <Row className="fields-box">
                    <Col span={24}>
                        <Form.Item
                            label="酒店名称"
                            name="hotel_name"
                            rules={[{required: true, message: '酒店名称是必填项！'}]}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="副标题"
                            name="subtitle"
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="供应商"
                            name="company_id"
                        >
                            <Select placeholder="选择供应商">
                                {supplie.map((item, i) => (
                                    <Option key={i} value={item.id}>{item.company_name}</Option>))}
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="所属行政地区"
                            name="city_id"
                            rules={[{required: true, message: '所属行政地区未填写！'}]}
                        >
                            <Cascader
                                fieldNames={{label: 'name', value: 'id', children: '_child'}}
                                options={area}
                                placeholder="请选择地区"
                                expandTrigger="hover"
                                onChange={areaOnChange}
                                showSearch={
                                    function filter(inputValue, path) {
                                        return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
                                    }
                                }
                                changeOnSelect
                            />
                        </Form.Item>

                        <Form.Item
                            label="酒店类型"
                            name="type_id"
                            rules={[{required: true, message: "酒店类型是必选项"}]}
                        >
                            <Select options={hotelTypeConf} placeholder={"选择酒店类型"}/>
                        </Form.Item>
                        <Form.Item
                            label="入住时间"
                            name="stay_stime"
                            rules={[{required: true, message: '入住时间是必选项！'}]}
                        >
                            <TimePicker format="HH:mm"/>
                        </Form.Item>
                        <Form.Item
                            label="退房时间"
                            name="check_out_stime"
                            rules={[{required: true, message: '退房时间是必选项！'}]}
                        >
                            <TimePicker format="HH:mm"/>
                        </Form.Item>
                        <Form.Item
                            label="酒店星级"
                            name="hotel_star_level"
                            rules={[{required: true, message: "酒店星级必选项"}]}
                        >
                            <Select placeholder={"选择酒店星级"} options={starLevelConf}/>
                        </Form.Item>

                        <Form.Item
                            label="所属品牌"
                            name="brand_id"
                        >
                            <Select placeholder={"选择品牌"} options={brandTypeConf}/>
                        </Form.Item>

                        <Form.Item
                            label="联系电话"
                            name="contact_way"
                            rules={[{required: true, message: '酒店联系电话是必填项！'}]}
                        >

                            <Input style={{width: 200}} placeholder={"请输入酒店联系方式,建议输入负责人手机号"}/>
                        </Form.Item>
                        <Form.Item
                            label="开业日期"
                            name="opening_date"
                            rules={[{required: true, message: '请选择酒店开业日期'}]}
                        >
                            <DatePicker format="YYYY-MM-DD"/>
                        </Form.Item>
                        <Form.Item
                            label="装修日期"
                            name="decorate_date"
                            rules={[{required: true, message: "请选择装修日期"}]}
                        >
                            <DatePicker format="YYYY-MM-DD"/>
                        </Form.Item>
                        <Form.Item
                            label="酒店地址"
                            name="hotel_address"
                            rules={[{required: true, message: '酒店地址是必填项！'}]}
                        >
                            <Input placeholder="请输入酒店详细地址"/>
                        </Form.Item>


                        {/*<Form.Item
                            label="景点描述"
                            name="scenic"
                        >
                            <Input placeholder="请输入景点描述"/>
                        </Form.Item>*/}

                        <Form.Item
                            label="景点"
                            name={"attractions_id"}
                        >
                            <Select
                                mode="multiple"
                                placeholder="选择酒店附近景点"
                                optionFilterProp="children"
                                onChange={handleChange}
                            >
                                {attractionConf}
                            </Select>

                        </Form.Item>


                        <Form.Item>
                            <Row gutter={8}>
                                <Col span={12}>
                                    <Form.Item
                                        label="酒店坐标"
                                        name={"lat-lon"}
                                        rules={[{required: true, message: '请输入真确格式的位置坐标'}]}
                                    >
                                        <Input placeholder={"填写经纬度，格式：纬度值,经度值"}/>
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Button type="link" href={lbs} target="_blank">点我去拾取位置坐标</Button>
                                </Col>
                            </Row>
                        </Form.Item>

                        <Form.Item
                            label="宠物"
                            name="carry_pet"
                        >
                            <Radio.Group placeholder="是否可以携带宠物">
                                <Radio value={1}>可以</Radio>
                                <Radio value={2}>不可以</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item
                            label="儿童床"
                            name="children_bed"
                        >
                            <Radio.Group placeholder="是否有儿童加床">
                                <Radio value={2}>没有</Radio>
                                <Radio value={1}>有</Radio>
                            </Radio.Group>
                        </Form.Item>


                        <Form.Item
                            label="早餐说明"
                        >
                            <Row gutter={10}>
                                <Col span={6}>
                                    <Form.Item
                                        name={"have_breakfast"}
                                    >
                                        <Radio.Group onChange={breakfastChange} value={2}>
                                            <Radio value={1}>含</Radio>
                                            <Radio value={2}>不含</Radio>
                                        </Radio.Group>


                                    </Form.Item>
                                </Col>
                                <Col span={6} style={{"display": disableBreakFirst ? "none" : ""}}>
                                    <Form.Item
                                        name={"breakfast_type"}
                                    >
                                        <Select placeholder="早餐形式" initialvalues={1}>
                                            <Select.Option value={1}>自助餐</Select.Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col span={6} style={{"display": disableBreakFirst ? "none" : ""}}>
                                    <Form.Item
                                        name={"breakfast_price"}
                                    >
                                        <InputNumber style={{width: "100%"}} placeholder="输入早餐价格" initialvalues={0}/>
                                    </Form.Item>
                                </Col>
                                <Col span={6} style={{"display": disableBreakFirst ? "none" : ""}}>
                                    <Form.Item
                                        name={"breakfast_business_time"}
                                    >
                                        <Input placeholder="输入营业时间描述"/>
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form.Item>

                        <Form.Item
                            label="是否有人群限制"
                            name="stay_in_limit"
                            labelCol={{span: 2.5}}
                        >
                            <Radio.Group value={2}>
                                <Radio value={1}>有限制</Radio>
                                <Radio value={2}>无限制</Radio>
                            </Radio.Group>
                        </Form.Item>

                        <Form.Item
                            label="简要描述"
                            name="simple_desc"
                            rules={[
                                {required: true, message: '简要描述必填！'}
                            ]}
                        >
                            <Ckeditor editorId="desc" readyHandler={(instan) => {
                                ck1 = instan;
                                ckReadyHandler(instan, 'simple_desc')
                            }} changeHandler={(instan) => ckChangeHandler('simple_desc', instan)}></Ckeditor>
                        </Form.Item>
                        <Form.Item
                            label="交通描述"
                            name="detail_traffic_desc"
                            rules={[
                                {required: true, message: '交通描述必填！'}
                            ]}
                        >
                            <Ckeditor editorId="intro" readyHandler={(instan) => {
                                ck2 = instan;
                                ckReadyHandler(instan, 'detail_traffic_desc')
                            }} changeHandler={(instan) => ckChangeHandler('detail_traffic_desc', instan)}></Ckeditor>
                        </Form.Item>

                        <Form.Item
                            label="大家都关注"
                        >
                            <Form.Item
                                noStyle
                                shouldUpdate
                            >
                                {({getFieldValue}) => (
                                    <Col span={24}>
                                        <Checkbox
                                            indeterminate={getFieldValue('focus').length > 0 && getFieldValue('focus').length < hotFocus.length}
                                            onChange={(v) => onCheckAllChange(0, v)}
                                            checked={getFieldValue('focus').length === hotFocus.length}
                                        >
                                            全选
                                        </Checkbox>
                                    </Col>
                                )}
                            </Form.Item>
                            <Form.Item
                                noStyle
                                name="focus"
                            >
                                <CheckboxGroup
                                    options={hotFocus}
                                    onChange={onChange}
                                />
                            </Form.Item>
                        </Form.Item>
                        <Form.Item
                            label="服务"
                        >
                            <Form.Item
                                noStyle
                                shouldUpdate
                            >
                                {({getFieldValue}) => (
                                    <Col span={24}>
                                        <Checkbox
                                            indeterminate={getFieldValue('services').length > 0 && getFieldValue('services').length < servicesConf.length}
                                            onChange={(v) => onCheckAllChange(1, v)}
                                            checked={getFieldValue('services').length === servicesConf.length}
                                        >
                                            全选
                                        </Checkbox>
                                    </Col>
                                )}
                            </Form.Item>
                            <Form.Item
                                noStyle
                                name="services"
                            >
                                <CheckboxGroup
                                    options={servicesConf}
                                    onChange={onChange}
                                />
                            </Form.Item>
                        </Form.Item>
                        <Form.Item
                            label="设施"
                        >
                            <Form.Item
                                noStyle
                                shouldUpdate
                            >
                                {({getFieldValue}) => (
                                    <Col span={24}>
                                        <Checkbox
                                            indeterminate={getFieldValue('facility_ids').length > 0 && getFieldValue('facility_ids').length < facilitiesConf.length}
                                            onChange={(v) => onCheckAllChange(2, v)}
                                            checked={getFieldValue('facility_ids').length === facilitiesConf.length}
                                        >
                                            全选
                                        </Checkbox>
                                    </Col>
                                )}
                            </Form.Item>
                            <Form.Item
                                noStyle
                                name="facility_ids"
                            >
                                <CheckboxGroup
                                    options={facilitiesConf}
                                    onChange={onChange}
                                />
                            </Form.Item>
                        </Form.Item>
                    </Col>
                </Row>
                <div style={{height: '20px'}}></div>
            </Form>
            <Row className="footer">
                <Col span={24} align="center">
                    <Button type="primary" onClick={onSubmit} loading={loading}>保存进入下一步</Button>
                </Col>
            </Row>
        </div>
    )
}

export default React.memo(BaseInfo);